package http

import (
	"bytes"
	"github.com/GoDistributedCacheFramework/src/cache"
	"github.com/GoDistributedCacheFramework/src/cluster"
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)


type Server struct {
	cache.Cache
	cluster.Node
}

func (s *Server) Listen()  {
	// 处理/cache/请求，即缓存的set，get，del操作
	http.Handle("/cache/",s.cacheHandler())
	http.Handle("/status",s.statusHandler())
	// 查看集群的节点列表
	http.Handle("/cluster",s.clusterHandler())
	// 节点再平衡
	http.Handle("/rebalance",s.clusterHandler())
	http.ListenAndServe(":12345",nil)
}

func New(c cache.Cache,n cluster.Node) *Server  {
	return &Server{c,n}
}

type cacheHandler struct {
	*Server
}

// 解析URL来获取key，并根据http请求的put，get，delete三种方法来调用cache.Cache中的
// set,get,del方法
func (h *cacheHandler) ServeHTTP(w http.ResponseWriter,r *http.Request)  {
	key := strings.Split(r.URL.EscapedPath(),"/")[2]
	if len(key) == 0{
		w.WriteHeader(http.StatusAccepted)
		return
	}
	m := r.Method
	if m == http.MethodPut {
		b,_ := ioutil.ReadAll(r.Body)
		if len(b) != 0 {
			e := h.Set(key,b)
			if e != nil {
				log.Println(e)
				w.WriteHeader(http.StatusInternalServerError)
			}
		}
		return
	}
	if m == http.MethodGet {
		b,e := h.Get(key)
		if e != nil {
			log.Println(e)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		if len(b) == 0 {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		w.Write(b)
		return
	}
	if m == http.MethodDelete {
		e := h.Del(key)
		if e != nil {
			log.Println(e)
			w.WriteHeader(http.StatusInternalServerError)
		}
		return
	}
	w.WriteHeader(http.StatusMethodNotAllowed)
}

func (s *Server) cacheHandler() http.Handler  {
	return &cacheHandler{s}
}


type statusHandler struct {
	*Server
}

// 调用cache.Cache中的getstat方法并返回 cache.Stat结构体用
// JSON 格式编码成字节切片的b，写入HTTP的响应正文
func (h *statusHandler) ServeHTTP(w http.ResponseWriter,r *http.Request)  {
	if r.Method != http.MethodGet {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	b,e := json.Marshal(h.GetStat())
	if e != nil {
		log.Println(e)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Write(b)
}

func (s *Server) statusHandler() http.Handler  {
	return &statusHandler{s}
}

type clusterHandler struct {
	*Server
}

func (h *clusterHandler) ServeHTTP(w http.ResponseWriter,r *http.Request)  {
	if r.Method != http.MethodGet {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	m := h.Members()
	b,e := json.Marshal(m)
	if e != nil {
		log.Println(e)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Write(b)
}

func (s *Server) clusterHandler() http.Handler  {
	return &clusterHandler{s}
}

type rebalanceHandler struct {
	*Server
}

func (h *rebalanceHandler) ServeHTTP(w http.ResponseWriter,r *http.Request)  {
	if r.Method != http.MethodPost {
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
	go h.rebalance()
}

func (h *rebalanceHandler) rebalance()  {
	s := h.NewScanner()
	defer s.Close()
	c := &http.Client{}
	for s.Scan() {
		k := s.Key()
		n,ok := h.ShouldProcess(k)
		if !ok {
			r,_ := http.NewRequest(http.MethodPut,
				"http://"+n+":12345/cache/"+k,
				bytes.NewReader(s.Value()))
			c.Do(r)
			h.Del(k)
		}
	}
}

func (s *Server) rebalanceHandler() http.Handler  {
	return &rebalanceHandler{s}
}

